import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// MVVM 公共视图层
class BaseView<T extends ChangeNotifier> extends StatefulWidget {
  final T model; //控制对应的数据

  final Widget Function(BuildContext context, T model, Widget child) builder; //绑定数据

  Function(T) onModelInit; //初始化数据方法

  final Widget child;

  BaseView({
    Key key,
    @required this.model,
    @required this.builder,
    this.onModelInit,
    this.child,
  }) : super(key: key);

  @override
  State createState() => _BaseViewState();
}

class _BaseViewState<T extends ChangeNotifier> extends State<BaseView<T>> {
  T model;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<T>(
      create: (_) => model,
      child: Consumer<T>(
        builder: widget.builder,
        child: widget.child,
      ),
    );
  }

  @override
  void initState() {
    model = widget.model;
    if ( model != null && widget.onModelInit != null ) {
      widget.onModelInit(widget.model);
    }
    super.initState();
  }
}
